package DBUtil;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil0 {
    // 配置信息作为属性
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    // 静态代码块，只会执行一次
    static {
        // 读取配置文件
        InputStream is = DBUtil.class.getClassLoader()
                .getResourceAsStream("jdbc.properties");
        // 创建 Properties 对象
        Properties properties = new Properties();
        try {
            // 通过 Properties 对象加载配置文件
            properties.load(is);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            // 加载驱动类
            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 创建连接
    public static Connection getConnection(){
        Connection con = null;
        try {
            // 2，获取连接
            con = DriverManager.getConnection(url,username,password);
        } catch ( SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    // 释放资源
    public static void close(AutoCloseable...autoCloseable){

        for (AutoCloseable closeable : autoCloseable) {
            if(closeable!=null){
                try {
                    closeable.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
